import './assets/main.css'
import 'reset-css/reset.css'
import { createApp, type App } from 'vue'
import { createPinia } from 'pinia'
import 'normalize.css/normalize.css' // 样式重置
import type { MicroGlobalData } from './stores/type'
import AppVue from './App.vue'
import router from './router'
import { ConfigProvider } from 'ant-design-vue'
// import './public-path' // qiankun 的 public-path 文件
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper'
import { useMicroGlobalData } from './stores/microGlobalData'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
let app: App<Element> | null = null

ConfigProvider.config({
  prefixCls: 'vue_antd',
  getPopupContainer: () => document.body
})
// app.use(createPinia())
// app.use(router)
const render = (container: HTMLElement | null | undefined) => {
  app = createApp(AppVue)

  app.component(ConfigProvider.name ?? '', ConfigProvider)
  app
    .use(router)
    .use(Antd)
    .use(createPinia())
    .mount(container ? container.querySelector('#app')! : '#app')
}

const initQianKun = () => {
  renderWithQiankun({
    mount(props: QiankunProps) {
      console.log('子应用挂载', props)
      const { actions, initialState } = props
      console.log('🚀 ~ mount ~ actions:', actions, initialState)
      const { container } = props
      render(container)
      // 在这里获取 Pinia store 实例
      const store = useMicroGlobalData()
      props.onGlobalStateChange((state: MicroGlobalData, prev: Record<string, any>) => {
        // state: 变更后的状态; prev 变更前的状态
        console.log('子应用 监听到变化', state, prev)
        store.initMicroGlobal(state)
        store.setActions(actions)
      })
    },
    bootstrap() {},
    unmount() {
      app?.unmount()
    },
    update: function (props: QiankunProps): void | Promise<void> {
      throw new Error('Function not implemented.')
    }
  })
}

qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render(null)

// app.mount('#app')
